package cn.ittaoli.szdz.controller;

import cn.ittaoli.szdz.model.DzJbxx;
import cn.ittaoli.szdz.model.DzJbxxXq;
import cn.ittaoli.szdz.service.DzJbxxService;
import cn.ittaoli.szdz.service.TestService;
import cn.ittaoli.utils.ExportExcel;
import cn.ittaoli.utils.FileUpload;
import cn.ittaoli.utils.JsonUtils;
import com.github.pagehelper.PageInfo;
import com.google.code.kaptcha.Constants;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by lub_lenovo on 2017/8/15.
 */
@Controller
@RequestMapping("/test")
public class TestController {

    @Autowired
    private TestService testService;

    @RequestMapping("/index")
    public String index(){
        return "test/index";
    }

    @RequestMapping("/verify")
    @ResponseBody
    public String verifyCode(String code, HttpServletRequest request){
        String codeCorrect=(String)request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
        System.out.println("shuru:"+code+";shengcheng:"+codeCorrect);
        if(codeCorrect.equals(code)) {
            System.out.println("验证通过 ");
        }

        return "shuru:"+code+";shengcheng:"+codeCorrect;
    }

    @RequestMapping("/jqgrid")
    public String jqgrid(){
        return "/test/jqgrid";
    }

    @RequestMapping("/getData")
    @ResponseBody
    public Map<String,Object> getData(Model model, @RequestParam(defaultValue = "1")Integer page, @RequestParam(defaultValue = "20")Integer rows,String q){
        Map<String,Object> map=new HashMap<>();

        PageInfo<DzJbxxXq> dzJbxxes=testService.getData(page,rows,q);
//        model.addAttribute("pageInfo",dzJbxxes);
//        Integer records=testService.getTotal();
        map.put("rows",dzJbxxes.getList());
        map.put("records",dzJbxxes.getTotal());
        map.put("total",dzJbxxes.getPages());
        map.put("page",dzJbxxes.getPageNum());
        return map;

    }

    @RequestMapping("/showInfo")
    public String showInfo(){
        return "/test/modal";
    }

    @RequestMapping("/addbscj")
    public String addbscj(){
        return "/test/addbscj";
    }


    @RequestMapping("/upexcel")
    @ResponseBody
    public String upexcel(@RequestParam("file")MultipartFile file,HttpServletRequest request) throws IOException {
        String path= FileUpload.upload(file,request);
        Map<String, Object> result = new HashMap<String,Object>();
        result.put("error", 0);
        result.put("message", "上传成功");
        result.put("url",path);
        try {
            InputStream is = new FileInputStream(request.getSession().getServletContext().getRealPath("")+path);
            HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);

            // 循环工作表Sheet
            for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) {
                HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
                if (hssfSheet == null) {
                    continue;
                }

                // 循环行Row
                for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
                    HSSFRow hssfRow = hssfSheet.getRow(rowNum);
                    if (hssfRow == null) {
                        continue;
                    }

                    // 循环列Cell
                    // "id","考生号","语文成绩","数学成绩","外语成绩"};
                    String id = getValue(hssfRow.getCell(1));
                    String ksh = getValue(hssfRow.getCell(2));
                    String ywcj = getValue(hssfRow.getCell(3));
                    String sxcj = getValue(hssfRow.getCell(4));
                    String wycj = getValue(hssfRow.getCell(5));

                }
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }




//        为了保证功能的兼容性，要把result的对象转换成json的字符串
        return JsonUtils.objectToJson(result);

    }

    private static String getValue(HSSFCell hssfCell) {
        if (hssfCell.getCellType() == hssfCell.CELL_TYPE_BOOLEAN) {
            // 返回布尔类型的值
            return String.valueOf(hssfCell.getBooleanCellValue());
        } else if (hssfCell.getCellType() == hssfCell.CELL_TYPE_NUMERIC) {
            // 返回数值类型的值
            return String.valueOf(hssfCell.getNumericCellValue());
        } else {
            // 返回字符串类型的值
            return String.valueOf(hssfCell.getStringCellValue());
        }

    }

    @RequestMapping("/export")
    @ResponseBody
    public String exportExcel(HttpServletResponse response) throws Exception {

        // 初始化HttpServletResponse对象
//        HttpServletResponse response = response..getResponse();

        // 定义表的标题
        String title = "员工列表一览";

        //定义表的列名
        String[] rowsName = new String[] { "考生号", "姓名", "身份证号", "语文成绩", "数学成绩","外语成绩"};

        //定义表的内容
        List<Object[]> dataList = new ArrayList<Object[]>();
        Object[] objs = null;
        PageInfo<DzJbxxXq> data = testService.getData(1, 20, "");

        List<DzJbxxXq> dzJbxxXqs=data.getList();
        for (int i = 0; i < dzJbxxXqs.size(); i++) {
            DzJbxxXq per = dzJbxxXqs.get(i);
            objs = new Object[rowsName.length];
            objs[0] = per.getKsh();
            objs[1] = per.getXm();
            objs[2] = per.getSfzh();
            objs[3] = per.getYwcj();
            objs[4] = per.getSxcj();
            objs[5] = per.getWycj();
//            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
//            String date = df.format(per.getJobtime());
//            objs[5] = date;
//            objs[6] = per.getResume();
//            objs[7] = per.getFilepath();
//            objs[8] = per.getDept().getDname();
            dataList.add(objs);
        }

        // 创建ExportExcel对象
        ExportExcel ex = new ExportExcel(title, rowsName, dataList);

        // 输出Excel文件
        try {
            OutputStream output = response.getOutputStream();
            response.reset();
            response.setHeader("Content-disposition",
                    "attachment; filename=PersonList.xls");
            response.setContentType("application/msexcel");
            ex.export(output);
            output.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "tolist";// 返回列表显示
    }

}
